package com.openroom.ui.component;

import java.net.URL;

import org.apache.pivot.wtk.Button;
import org.apache.pivot.wtk.ButtonPressListener;
import org.apache.pivot.wtk.LinkButton;
import org.apache.pivot.wtk.content.ButtonData;

import com.openroom.db.DBHelper;
import com.openroom.event.ApplicationEvent;
import com.openroom.event.EventHandler;
import com.openroom.event.EventManager;
import com.openroom.event.EventType;
import com.openroom.model.ModelLocator;
import com.openroom.model.Photograph;
import com.openroom.ui.MainWindow;

public class SelectButton extends LinkButton {
    URL unselectedResource = MainWindow.class.getClassLoader().getResource(
            "com/openroom/ui/select_white.png");
    URL selectedResource = MainWindow.class.getClassLoader().getResource(
            "com/openroom/ui/select.png");

    public SelectButton() {
        getUserData().put("SELECTED", false);
        getButtonPressListeners().add(new ButtonPressListener() {
            @Override
            public void buttonPressed(Button arg0) {
                ButtonData buttonData = (ButtonData) arg0.getButtonData();
                Boolean selected = (Boolean) arg0.getUserData().get("SELECTED");
                Photograph photograph = ModelLocator.getInstance().getCurrentlySelectedImage();
                if (selected) {
                    buttonData.setIcon(unselectedResource);
                    arg0.getUserData().put("SELECTED", false);
                    ModelLocator.getInstance().selectImage();
                }
                else
                {
                    buttonData.setIcon(selectedResource);
                    arg0.getUserData().put("SELECTED", true);
                    ModelLocator.getInstance().unSelectImage();
                }
                arg0.setVisible(false);
                arg0.setVisible(true);
            }
        });

        EventManager.getInstance().listenToEventType(new EventHandler() {
            @Override
            public void handle(ApplicationEvent event) {
                Photograph photograph = ModelLocator.getInstance().getCurrentlySelectedImage();
                if (photograph == null)
                {
                    ((ButtonData) getButtonData()).setIcon(unselectedResource);
                    return;
                }
                if (photograph.isSelected())
                {
                    ((ButtonData) getButtonData()).setIcon(selectedResource);
                } else
                {
                    ((ButtonData) getButtonData()).setIcon(unselectedResource);
                }
                setVisible(false);
                setVisible(true);
            }
        }, EventType.CURRENT_IMAGE_CHANGED, EventType.CURRENT_STATUS_CHANGE);
    }
}
